# _*_ coding:utf-8 _*_
# @Time  : 2023.05.17
# @Author: zizlee
import hashlib
from fastapi import APIRouter, Body, Query
from pydantic import BaseModel, validator, conint
from utils import datetime_utils
from db_utils import BaseDatabaseConnection
from response import APIResponse
from constant.message import ShortFastMessage


class ShortMessageItem(BaseModel):
    msg_time: str
    content: str

    @validator('msg_time')
    def validate_msg_time(cls, value):
        time = datetime_utils.auth_yyyy_mm_dd_hhmmss(value, tsep=':')
        if not time:
            raise ValueError('msg_time formate Error: 接受`YYYY-MM-DD HH:MM:SS`')
        return time

class CreateShortMessageItem(ShortMessageItem):
    msg_type: int

    @validator('msg_type')
    def validate_msg_type(cls, value):
        if value not in ShortFastMessage.CATEGORIES:
            raise ValueError('msg_type Error,请查阅对接类型.')
        return value

class UpdateShortMessageItem(ShortMessageItem):
    rid: int
    is_active: conint(ge=0, le=1)


class ShortMessage:
    def __init__(self, page: int = 1, page_size: int = 30):
        self.page = page
        self.page_size = page_size

    def save_short_message(self, msg: CreateShortMessageItem):
        md5_hash = hashlib.md5(msg.content.encode('utf8')).hexdigest()
        sql = """
            INSERT IGNORE INTO infor_short_message(msg_time,msg_type,content,md5)
            VALUES (%s,%s,%s,%s);
        """
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute(sql, [msg.msg_time, msg.msg_type, msg.content, md5_hash])
        return APIResponse.success(msg='保存讯息完成!')

    def update_short_message(self, msg: UpdateShortMessageItem):
        md5_hash = hashlib.md5(msg.content.encode('utf8')).hexdigest()
        sql = "UPDATE infor_short_message SET msg_time=%s,content=%s,is_active=%s,md5=%s WHERE id=%s LIMIT 1;"
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute(sql, [msg.msg_time, msg.content, msg.is_active, md5_hash, msg.rid])
        return APIResponse.success(msg='更新完成.')

    def get_short_message(self, msg_type: int):
        if msg_type not in ShortFastMessage.CATEGORIES:
            return APIResponse.validate_error(detail='查询的数据类型错误!')
        sql = """
            SELECT id,msg_time,msg_type,content,is_active FROM infor_short_message 
            WHERE msg_type=%s ORDER BY msg_time DESC;
        """
        with BaseDatabaseConnection() as conn:
            results = conn.query_paginator(sql, param=[msg_type],
                                           page=self.page, page_size=self.page_size)
        return APIResponse.success(data=results)


short_message_api = APIRouter()


@short_message_api.post('/create/')
def save_short_message(msg: CreateShortMessageItem = Body(...)):
    return ShortMessage().save_short_message(msg=msg)


@short_message_api.get('/retrieve/')
def get_short_message(msg: int = Query(...), page: int = Query(1), page_size: int = Query(30)):
    return ShortMessage(page=page, page_size=page_size).get_short_message(msg_type=msg)


@short_message_api.put('/update/')
def update_short_message(msg: UpdateShortMessageItem = Body(...)):
    return ShortMessage().update_short_message(msg=msg)
